/**
 * @Author: wilmerxu
 * @Description: ajax请求封装
 * @Date: 2020/8/8 12:10
 */
class Ajax {
  /**
   * @Description 发送HTTP请求
   * @Param String url 接口地址
   * @Param String method 调用方法
   * @Param Object data 入参对象
   * @Param Function callback 返回函数
   **/
  sendXMLHttpRequest(url, method, data = {}, callback) {
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = (_data) => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          const res = JSON.parse(xhr.responseText || '');
          callback(res);
        } else {
          throw new Error(_data);
        }
      }
    };
    xhr.open(method, url, true);
    if (method == 'POST') {
      xhr.send(JSON.stringify(data));
    } else {
      xhr.send();
    }
  }

  /**
   * @Description post调用接口
   * @Param Object options 调用入参对象
   * @return Promise
   **/
  $post (options) {
    return new Promise(((resolve, reject) => {
      const {url, data = {}, method = 'POST'} = options;
      this.sendXMLHttpRequest(url, method, data, (res) => {
        if (res) {
          resolve(res);
        } else {
          reject(false);
        }
      });
    }));
  }
}

export default new Ajax();
